<template>
	<view class="flex">
		<view @click="sub" class="font-md text-center flex justify-center align-center"
			style="background-color: #eee;width: 50rpx;height: 50rpx;">-</view>
		<view class="flex justify-center align-center font"
			style="border-left: 2rpx solid #ddd; border-right: 2rpx solid #ddd;width: 50rpx;height: 50rpx;background-color: #eee;">
			<input @change="change" v-model="Quantity" type="number" class="w-100 text-center" />
		</view>
		<view @click="add" class="font-md text-center flex justify-center align-center"
			style="background-color: #eee;width: 50rpx;height: 50rpx;">+</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				Quantity: 1
			}
		},
		props: {
			num: {
				type: Number,
				default: 1
			},
			max: {
				type: Number,
				default: 0
			},
			loading: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			num: function(e) {
				this.Quantity = e
			}
		},
		methods: {
			add() { //添加
				if (!this.loading) {
					if (this.max == 0) {
						this.Quantity++
						this.$emit('Count', this.Quantity)
						this.$emit('Type', 'add')
					} else {
						if (this.Quantity * 1 < this.max * 1) {
							this.Quantity++
							this.$emit('Count', this.Quantity)
							this.$emit('Type', 'add')
						} else {
							this.$emit('Count', this.max)
							this.$emit('Type', 'add')
							uni.showToast({
								title: '已经最大值了!',
								icon: 'none'
							})
						}
					}
				}
			},
			sub() { //减
				if (!this.loading) {
					if (this.Quantity > 1) {
						this.Quantity--;
						this.$emit('Count', this.Quantity)
						this.$emit('Type', 'sub')
					} else {
						uni.showToast({
							title: "至少选择一件商品！",
							icon: "none",
						});
					}
				}
			},
			change() { //查询
				//判断是否为数字
				console.log(this.max);
				if (!isNaN(parseFloat(this.Quantity)) && isFinite(this.Quantity)) {
					this.$emit('Count', parseInt(this.Quantity))
					if (this.max == 0) {
						this.$emit('Count', parseInt(this.Quantity))
					} else {
						if (parseInt(this.Quantity) < parseInt(this.max)) {
							this.$emit('Count', this.Quantity)
						} else {
							this.$emit('Count', this.max)
						}
					}
				} else {
					this.Quantity = 1
					this.$emit('Count', this.Quantity)
				}
			}
		},
		mounted() {
			this.Quantity = this.num
		}
	}
</script>

<style>

</style>